package com.bluelight.expertsystemmobile.versionupdate.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.bluelight.expertsystemmobile.versionupdate.dao.VersionDao;
import com.bluelight.expertsystemmobile.versionupdate.entity.Version;

import support.action.BaseAction;

@ParentPackage(value = "json-default")
@Namespace("/")
@Action(value = "/fileDownload", results = {
		@Result(name = "json", type = "json"),
		@Result(name = "success", location = "/index.jsp"),
		@Result(name = "download", type = "stream", params = { "contentType", "application/octet-stream", "inputName", "inputStream", "contentDisposition",
				"attachment;filename=\"${fileName}\"", "bufferSize", "4096" }) })
public class FileDownloadAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private String fileName;// 初始的通过param指定的文件名属性
	@Autowired
	private VersionDao versionDao;

	private Version version;

	public void setVersion(Version version) {
		this.version = version;
	}

	public Version getVersion() {
		return version;
	}

	@Override
	public String execute() throws Exception {
		if(getFileName()==null){
			this.setFileName(versionDao.queryLastFileName());
		}
		return DOWNLOAD;
	}


	public InputStream getInputStream() throws Exception {
		// root项目上传图片路径，UPLOAD_ROOT_PATH定义为常量，从配置文件里取值
		// url就是附件在服务器上对应的路径
		
		PropertiesConfiguration p = new PropertiesConfiguration("upload.properties");
		String uploadPath = p.getString("upload.apk.path");
		String path = ServletActionContext.getRequest().getRealPath(uploadPath) + "\\" + this.fileName;
		return new FileInputStream(new File(path));
	}

	public void setFileName(String fileName) throws UnsupportedEncodingException {
		this.fileName = fileName;
//		String agent = ServletActionContext.getRequest().getHeader("User-agent");
//		// 如果浏览器是IE浏览器，就得进行编码转换
//		if (agent.contains("MSIE")) {
//			this.fileName = URLEncoder.encode(fileName, "UTF-8");
//		} else {
//			this.fileName = new String(fileName.getBytes(), "ISO-8859-1");
//		}
	}

	public String getFileName() {
		return fileName;
	}

}
